import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_dk_form/flutter_dk_form.dart';
import 'package:unicorndial/unicorndial.dart';
import 'package:flutter_dynamic_forms/flutter_dynamic_forms.dart';
import 'package:dynamic_forms/dynamic_forms.dart';
import 'package:flutter_dk_form/flutter_dk_form.dart' as components;
import 'package:flutter/services.dart';

class DkDynamicFormDemoPage extends StatefulWidget {
  static const String routeName = '/page/dynamic_form_demo_page';
  static const String name = "DkDynamicFormDemoPage";

  @override
  DkDynamicFormDemoState createState() => DkDynamicFormDemoState();
}

class DkDynamicFormDemoState extends State<DkDynamicFormDemoPage> {
  GlobalKey<DkFormState> _formKey = GlobalKey<DkFormState>();
  FormRenderService _formRenderService;
  FormManager _formManager;
  FormElement _form;

  @override
  void initState() {
    super.initState();
    _buildForm();
  }

  Future _buildForm() async {
    _formRenderService = FormRenderService(
      renderers: components.getRenderers(),
      dispatcher: _onFormElementEvent,
    );
    var parsers = components.getParserList();
    FormParserService parserService = JsonFormParserService(parsers);
    var formManagerBuilder = FormManagerBuilder(parserService);
    var content =
        await rootBundle.loadString('assets/user_info.json', cache: false);
    _formManager = formManagerBuilder.build(content);
    setState(() {
      _form = _formManager.form;
    });
  }

  void _onFormElementEvent(FormElementEvent event) {
    if (event is ChangeValueEvent) {
      _formManager.changeValue(
          value: event.value,
          elementId: event.elementId,
          propertyName: event.propertyName,
          ignoreLastChange: event.ignoreLastChange);
    }
  }

  @override
  Widget build(BuildContext context) {
    Widget widget = _form == null
        ? CircularProgressIndicator()
        : _formRenderService.render(_form, context);
    return Scaffold(
      appBar: AppBar(
        title: Text('DkFormFieldDemoPage'),
      ),
      floatingActionButton: UnicornDialer(
        backgroundColor: Color.fromRGBO(255, 255, 255, 0.6),
        parentButtonBackground: Colors.redAccent,
        orientation: UnicornOrientation.VERTICAL,
        parentButton: Icon(Icons.add),
        childButtons: createButtons(),
      ),
      body: SafeArea(
        child: SingleChildScrollView(
          child: DkForm(
            key: _formKey,
            autovalidate: false,
            child: widget,
          ),
        ),
      ),
    );
  }

  void _forSubmitted() {
    var _form = _formKey.currentState;
    if (_form.validate()) {
      _form.save();
      print(json.encode(_form.value));
    }
    print('error text:${_form.errorText}');
  }

  void _forReset() {
    var _form = _formKey.currentState;
    _form.reset();
  }

  List<UnicornButton> createButtons() {
    var childButtons = List<UnicornButton>();
    childButtons.add(UnicornButton(
      currentButton: FloatingActionButton(
        heroTag: 'reset',
        child: Text('Rest'),
        onPressed: _forReset,
      ),
    ));
    childButtons.add(UnicornButton(
      currentButton: FloatingActionButton(
        child: Text('Save'),
        onPressed: _forSubmitted,
      ),
    ));
    return childButtons;
  }
}
